package com.example.logisticsingle.utils;


import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.authorization.AuthProperties;
import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.entity.SSOUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 单点登录登录铺助类
 * @author Roskin
 *
 */
public class SSOTokenLoginHelper {
	
	
	public static SSOUser loginCheck(HttpServletRequest request, HttpServletResponse response){
    	String token = getTokenByRequest(request);
        // cookie user
        SSOUser ssoUser = (StringUtils.isNotNull(token) &&token.startsWith(AuthProperties.token.prefix))?loginCheck(token):null;
        if (ssoUser != null) {
            return ssoUser;
        }

        // remove old cookie
        CookieUtil.remove(request, response, Config.SSO_SESSIONID);

        // set new cookie
        token = request.getParameter(Config.SSO_SESSIONID);
        ssoUser = SSOTokenLoginHelper.loginCheck(token);
        if (ssoUser != null) {
            CookieUtil.set(response, Config.SSO_SESSIONID, token, false);    // expire when browser close （client cookie）
            return ssoUser;
        }
        return null;
    }
	/**
	 * 获取请求的Token
	 * @param request
	 * @return
	 */
	public static String getTokenByRequest(HttpServletRequest request) {
		String token = request.getHeader(AuthProperties.token.header);
    	token = StringUtils.isNotNull(token)? token:request.getParameter(Config.ACCESS_TOKEN);
    	String request_type = request.getHeader(Config.REQUEST_TYPE);
		if(StringUtils.isNotNull(token)&&StringUtils.isNotNull(request_type) && Integer.valueOf(request_type)==Config.REQUEST_TYPE_WEB) {
    		token = CookieUtil.getValue(request, Config.SSO_SESSIONID);
    	}
    	return token;
	}
	
	 /**
	  * 	根据Token获取用户信息
	  * @param token
	  * @return
	  */
	 public static SSOUser loginCheck(String token) {
		/*
		 * if(StringUtils.isNull(token)) { SSOUserDetail principal = (SSOUserDetail)
		 * SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return
		 * principal.getSsoUser(); }
		 */
		 return SSOLoginStoreHelper.get(token);
	 }
	/**
	 * logout 操作，通过request请求
	 * @param request
	 */
	 public static void logout(HttpServletRequest request) {
		 String headerSessionId = request.getHeader(Config.SSO_SESSIONID);
	     logout(headerSessionId);
	 }
	 /**
	  * 登出操作
	  * @param token
	  */
	 public static void logout(String token) {
	     if (StringUtils.isNotNull(token)) 
	    	 SSOLoginStoreHelper.remove(token);
	 }
	 /**
	  *	生成Token信息
	  * @return
	  */
	 public static String generatorToken() {
		 return UUID.randomUUID().toString().replaceAll("-", "");
	 }
}
